package com.fita.wechat.service.impl;


import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.persistence.annotation.Dao;
import com.fita.entity.agent.Agent;
import com.fita.entity.agent.AgentApply;
import com.fita.entity.agent.AgentCompany;
import com.fita.entity.agent.AgentType;
import com.fita.entity.coupon.Coupon;
import com.fita.entity.coupon.CouponStatus;
import com.fita.entity.principal.District;
import com.fita.wechat.Constant;
import com.fita.wechat.dao.AgentAuditDao;
import com.fita.wechat.dao.AgentDao;
import com.fita.wechat.dao.CouponDao;
import com.fita.wechat.dto.AgentApplyRequest;
import com.fita.wechat.handler.SmsHandler;
import com.fita.wechat.service.AgentApplyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 宋剑宏
 */
@Service("agentApplyService")
public class AgentApplyServiceImpl extends DataServiceImpl<AgentApply> implements AgentApplyService {

    private static final Logger logger = LoggerFactory.getLogger(AgentApplyServiceImpl.class);

    @Autowired
    private GenericDaoSupport genericDaoSupport;

    @Dao
    private AgentDao agentDao;

    @Dao
    private CouponDao couponDao;

    @Dao
    private AgentAuditDao agentAuditDao;

    @Autowired
    private SmsHandler smsHandler;

    /*
     * (non-Javadoc)
     * @see com.fita.wechat.service.AgentApplyService#createAgentApply(com.fita.wechat.dto.AgentApplyRequest, java.lang.String)
     */
    public void createAgentApply(AgentApplyRequest agentApplyRequest, String openid, Long primaryAgentId) {

        // 1. validate agentApplyRequest
        if (!agentApplyRequest.validate()) {
            throw BusinessException.newInstance("400", "代理人申请参数错误");
        }

        // 2. load & validate district
        District district = genericDaoSupport.load(District.class, agentApplyRequest.getDistrictId());
        if (district == null) {
            throw BusinessException.newInstance("400", "该分区不存在");
        }

        Agent agent = agentDao.load(agentApplyRequest.getMobile());
        AgentApply existAgentApply = agentDao.loadAgentApply(agentApplyRequest.getMobile());
        if (agent != null) {
            throw new BusinessException("该代理已存在");
        }
        if (existAgentApply != null){
            throw new BusinessException("代理申请已存在");
        }

        // 3. do save agent apply
        AgentApply agentApply = agentApplyRequest.generateAgentApply(district);

        if (agentApplyRequest.getPrimaryAgentId() != null) {

            Agent primaryAgent = genericDaoSupport.load(Agent.class, agentApplyRequest.getPrimaryAgentId());

            agentApply.bindPrimaryAgent(primaryAgent, agentApplyRequest.getRate());
        }
        genericDaoSupport.save(agentApply.bindOpenid(openid).initliaze());

        // 二级代理直接注册成功
        if (agentApplyRequest.getPrimaryAgentId() != null) {
            // 设置销售
            Agent primaryAgent = genericDaoSupport.load(Agent.class, primaryAgentId);
            agentApply.principal(primaryAgent.getCompany().getPrincipal());

            // 设置分区
            agentApply.editDistrict(primaryAgent.getDistrict());

            this.verified(agentApply.getId());
        }
    }


    /*
     * (non-Javadoc)
     *
     * @see com.fita.wechat.service.AgentApplyService#loadAgentApply(java.lang.Long)
     */
    public AgentApply load(Long id) {
        return genericDaoSupport.load(AgentApply.class, id);
    }


    public void verified(Long id) {
        //8元优惠券
        long templateId1 = 1;
        //10元优惠券
        long templateId2 = 2;
        //30元优惠券
        long templateId3 = 3;
        Coupon coupon1 = couponDao.loadSingleCoupon(CouponStatus.UNCLAIMED, templateId1);
        List<Coupon> coupons2 = couponDao.loadManyCoupon(CouponStatus.UNCLAIMED, templateId2, 0, 2);
        List<Coupon> coupons3 = couponDao.loadManyCoupon(CouponStatus.UNCLAIMED, templateId3, 0, 2);

        AgentApply agentApply = genericDaoSupport.load(AgentApply.class, id);
        String companyName = agentApply.getCompanyName();
        AgentCompany agentCompany = agentApply.generateAgentCompany();
        //公司代理
        if (agentApply.getType().equals(AgentType.COMPANY)) {

            //公司名字是否为空
            if (agentApply.getCompanyName() == null) {
                throw new BusinessException("公司不可为空！");
            }

            Agent agents = null;
            AgentCompany agentCompanyd = agentAuditDao.load(companyName);
            //公司已存在
            if (agentCompanyd != null) {
                // 如果存在公司不是二级公司
                if (agentCompanyd.getPrimaryAgent() == null){
                    throw BusinessException.newInstance("500", "代理公司已存在，请联系客服。code：001");
                }
                if (agentCompanyd.getPrimaryAgent() != agentApply.getPrimaryAgent()){
                    throw BusinessException.newInstance("500", "代理公司已存在，请联系客服。code：002");
                }
                agents = new Agent(agentApply, agentCompanyd);
                genericDaoSupport.save(agents);
            } else {
                //创建二级公司
                genericDaoSupport.save(agentCompany.create());
                AgentCompany agentCompanys = agentAuditDao.load(companyName);
                agents = new Agent(agentApply, agentCompanys);
                //二级公司绑定一级代理
                agentCompanys.bingPrimaryAgent(agentApply.getPrimaryAgent(), agentApply.getRate());
                genericDaoSupport.update(agentCompanys);
                //创建代理人
                genericDaoSupport.save(agents);
            }
            //发放优惠券
            if (coupon1 != null && coupons2 != null && coupons3 != null) {

                logger.info("userId [{}] mobile [{} coupon1 name [{}]", agents.getId(), agents.getMobile(), coupon1.getTemplate().getName());

                //优惠券1
                genericDaoSupport.update(coupon1.identify(agents.getId(), agents.getMobile(), agents.getName()));

                genericDaoSupport.update(coupon1.getBatch().editClaimedAmount());

                logger.info("userId [{}] mobile [{} coupon1 name [{}]", agents.getId(), agents.getMobile(), coupon1.getTemplate().getName());

                for (Coupon coupon : coupons2) {
                    //优惠券2  两张
                    genericDaoSupport.update(coupon.identify(agents.getId(), agents.getMobile(), agents.getName()));

                    genericDaoSupport.update(coupon.getBatch().editClaimedAmount());

                    logger.info("userId [{}] mobile [{} coupon2 name [{}]", agents.getId(), agents.getMobile(), coupon.getTemplate().getName());
                }

                for (Coupon coupon : coupons3) {
                    //优惠券3 两张
                    genericDaoSupport.update(coupon.identify(agents.getId(), agents.getMobile(), agents.getName()));

                    genericDaoSupport.update(coupon.getBatch().editClaimedAmount());
                    logger.info("userId [{}] mobile [{} coupon3 name [{}]", agents.getId(), agents.getMobile(), coupon.getTemplate().getName());
                }
            }

        } else {
            //个人代理
            genericDaoSupport.save(agentCompany.create());
            AgentCompany agentCompanys = agentAuditDao.loadByMobile(agentApply.getMobile());
            agentCompanys.bingPrimaryAgent(agentApply.getPrimaryAgent(), agentApply.getRate());
            genericDaoSupport.update(agentCompanys);
            Agent agents = new Agent(agentApply, agentCompanys);
            genericDaoSupport.save(agents);

            //发放优惠券
            if (coupon1 != null && coupons2 != null && coupons3 != null) {

                //优惠券1
                genericDaoSupport.update(coupon1.identify(agents.getId(), agents.getMobile(), agents.getName()));

                genericDaoSupport.update(coupon1.getBatch().editClaimedAmount());

                for (Coupon coupon : coupons2) {
                    //优惠券2  两张
                    genericDaoSupport.update(coupon.identify(agents.getId(), agents.getMobile(), agents.getName()));

                    genericDaoSupport.update(coupon.getBatch().editClaimedAmount());
                }
                for (Coupon coupon : coupons3) {
                    //优惠券3 两张
                    genericDaoSupport.update(coupon.identify(agents.getId(), agents.getMobile(), agents.getName()));

                    genericDaoSupport.update(coupon.getBatch().editClaimedAmount());
                }
            }
        }
        genericDaoSupport.update(agentApply.verified());
        String content = "【" + Constant.SMS_ORDER_COMPANY_NAME + "】尊敬的用户，您的飞腾会会员已经注册成功。海外自驾就选飞腾会：www.fita-club.com";
        smsHandler.sendAuditSuccessMessage(agentApply.getMobile(), content);

    }

    ;

}
